package com.example.jdbc.login;

import java.sql.*;
import java.util.Objects;
import java.util.Scanner;

/**
 * 需要使用Statement的场景，例如升序降序
 */
public class Demo6 {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("请输入desc或asc，desc表示降序，asc表示升序");
        System.out.print("请输入: ");
        String keyWord = s.nextLine();
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs  = null;
        try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://192.168.31.92:3306/test", "root", "123456");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from muser order by id " + keyWord);
            while (rs.next()) {
                System.out.println();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (Objects.nonNull(rs)) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (Objects.nonNull(stmt)) {
                try {
                    stmt.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
            if (Objects.nonNull(conn)) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }
}
